package com.crowntit.trigger.job;

import com.alibaba.fastjson.JSON;
import com.crowntit.domain.trade.service.ITradeOrderSettlementService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class GroupBuyNotifyJob {

    @Resource
    private ITradeOrderSettlementService tradeOrderSettlementService;

    @Resource
    private RedissonClient redissonClient;


    @Scheduled(cron = "0/15 * * * * ?")
    public void exec(){
        log.info("定时任务：拼团完成回调通知 开始");
        RLock lock = redissonClient.getLock("group_buy_market_notify_job_exec");

        try {
            boolean isLocked = lock.tryLock(3, 0, TimeUnit.SECONDS);
            if (!isLocked) return;

            Map<String, Integer> result = tradeOrderSettlementService.execSettlementNotifyJob();
            log.info("定时任务：拼团完成回调通知 执行成功: {}", JSON.toJSONString(result));
        } catch (Exception e){
            log.error("定时任务：拼团完成回调通知 执行失败", e);
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }
}
